package org.jeecg.modules.xmss.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.xmss.entity.XmssTowns;
import org.jeecg.modules.xmss.service.IXmssTownsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/sys/wxAuth")
@Api(tags = "微信授权登录")
@Slf4j
public class WxLoginController {


    @Autowired
    private IXmssTownsService iXmssTownsService;
    /**
     * 图形验证码
     * @param
     * @return
     */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    @AutoLog(value = "微信登录接口")
    @ApiOperation(value="公众号接口--微信登录接口", notes="jqk")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信授权code码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "appId", value = "乡镇的公众号标识--txzrd", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "secret", value = "乡镇的公众号标识--txzrd", required = false, dataType = "String", paramType = "query"),
    })
    public Result<String> wxLogin(@RequestParam(name="code") String code,@RequestParam(name="appId") String appId,@RequestParam(name="secret") String secret) {
        Result<String> result = new Result<String>();
        try {
                //获取access_token
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
                Map<String, Object> map1 = new HashMap<>();//存放参数
                map1.put("appid", appId);
                map1.put("secret", secret);
                map1.put("code", code);
                map1.put("grant_type", "authorization_code");
                String jsonObjectStr = HttpUtil.createGet(url).form(map1).execute().body();
                //返回结果的json对象
                JSONObject resultObject = JSON.parseObject(jsonObjectStr);
                String openId = resultObject.getString("openid");
                log.info("openId:" + openId);
                result.setResult(openId);
                return result;
        } catch (Exception e) {
            result.error500("获取openId出错" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


}
